package org.example.myleet.p890;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        char[] patterChars = pattern.toCharArray();
        List<String> result = new ArrayList<>(words.length);
        for (String word : words) {
            if (isMapping(word.toCharArray(), patterChars)) {
                result.add(word);
            }
        }
        return result;
    }

    private boolean isMapping(char[] word, char[] pattern) {
        char[] pMapping = new char[128];
        boolean[] existW = new boolean[128];
        for (int i = 0; i < word.length; ++i) {
            char w = word[i];
            char p = pattern[i];
            if (pMapping[p] > 0) {
                char m = pMapping[p];
                if (w != m) {
                    return false;
                }
            } else {
                if (existW[w]) {
                    return false;
                }
                pMapping[p] = w;
                existW[w] = true;
            }
        }
        return true;
    }
}
